package Helpers;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.log4j.*;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class ApplicationLogger  {
	public final Logger LOG = Logger.getLogger(ApplicationLogger.class);

	private static final class Nested
    {
        static final ApplicationLogger _instance = new ApplicationLogger();
    }
	 
	private ApplicationLogger()
	{
		Appender a = null;
		try {
			a = new FileAppender(new PatternLayout(), GetPathToLogFile());
		} catch (IOException e) {
			e.printStackTrace();
		}
		BasicConfigurator.configure(a);
	}

    public static ApplicationLogger getInstance()
    {
          return Nested._instance;
    }
    
    private static Document LoadLogSettingsXML()
    {
    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		try {
			db = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		
		Document doc = db.newDocument();
		try {
			doc = db.parse(new File("webapps/EVO-MED/AppConfig/LogSettings.xml"));
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        return doc;
    }
    
    private static String GetPathToLogFile()
    {
    	XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		XPathExpression log_expr = null;
		
		try {
			log_expr = xpath.compile("//PathToLogFile/text()");
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		
		String path = "";
		try {
			path = (String) log_expr.evaluate(LoadLogSettingsXML(), XPathConstants.STRING);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}

        return path;
    }
    
}
